<?php
session_start();
$upload=1;
include 'header.php';
echo "<br>";
echo '<main id="content">';
?>



<form action="upload.php" method="post" title="Upload Image" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" title="Select File" id="fileToUpload"> <br>License:
  <input type="text" name="license" title="License" value="CC By SA 4.0"> <br> Description (important for accessability!):
  <input type="text" name="alt" title="Alt Text of Image" onfocus="this.value=''" value="Please provide a short description of the image"> <br>
  <input type="submit" value="Upload Image" title="Submit" name="submit">
</form>


 <?php
if(isset($_POST['submit']))
{
 if($_SESSION['Name']!="" && $_SESSION['Level']>=$ImagePermissionLevel)
 {



 
$target_dir = "images/";
$target_file = $target_dir . bin2hex(random_bytes(5)) . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
  
// if everything is ok, try to upload file
} else {
	$target_file = $target_dir . bin2hex(random_bytes(5)) . '.' . $imageFileType;
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
	  $sql = "INSERT INTO Images (Link, Unlocked, Uploader, License, Alt) VALUES (?, '0', ?, ?, ?)";
	  if($_SESSION['Level']>=$ImageAutoLevel)
	  $sql = "INSERT INTO Images (Link, Unlocked, Uploader, License, Alt) VALUES (?, '1', ?, ?, ?)";
	  $stmt = $conn->prepare($sql); 
	  $in1=$target_file;
	  $in2=intval($_SESSION['ID']);
	  $in3=$_POST['license'];
	  $in4=$_POST['alt'];
	  $stmt->bind_param("siss", $in1, $in2, $in3, $in4);

	  $stmt->execute();
	

    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded. It will appear in the gallery as soon as it has been checked by the moderation team.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
}
else
{
	echo "No permission for image upload";
}
}
?> 
</main>
</body>
</html>
